import SwiftUI
import Combine

class WebSocketManager: ObservableObject {
    @Published var isConnected = false
    @Published var keyStates = ["x": false, "z": false]
    @Published var responseText = "等待连接..."

    private var webSocketTask: URLSessionWebSocketTask?
    private let serverURL = URL(string: "ws://192.168.1.3:5000/ws")!

    func connect() {
        let session = URLSession(configuration: .default)
        webSocketTask = session.webSocketTask(with: serverURL)
        webSocketTask?.resume()

        responseText = "正在连接..."
        receiveMessage()

        DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
            self.isConnected = self.webSocketTask?.state == .running
            if self.isConnected {
                self.responseText = "已连接到服务器"
                self.sendMessage(action: "get_state", key: "")
            } else {
                self.responseText = "连接失败"
            }
        }
    }

    func disconnect() {
        webSocketTask?.cancel(with: .normalClosure, reason: nil)
        isConnected = false
        responseText = "已断开连接"
    }

    private func receiveMessage() {
        webSocketTask?.receive { [weak self] result in
            guard let self = self else { return }

            switch result {
            case .success(let message):
                switch message {
                case .string(let text):
                    print("收到消息: \(text)")
                    self.handleMessage(text)
                case .data(let data):
                    if let text = String(data: data, encoding: .utf8) {
                        print("收到数据消息: \(text)")
                        self.handleMessage(text)
                    }
                @unknown default:
                    break
                }

                // 继续接收下一条消息
                self.receiveMessage()

            case .failure(let error):
                print("WebSocket接收错误: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    self.isConnected = false
                    self.responseText = "连接错误: \(error.localizedDescription)"
                }
            }
        }
    }

    private func handleMessage(_ text: String) {
        guard let data = text.data(using: .utf8),
              let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
            print("JSON解析失败: \(text)")
            return
        }

        DispatchQueue.main.async {
            // 处理状态更新消息
            if let type = json["type"] as? String, type == "state_update",
               let states = json["key_states"] as? [String: Bool] {
                self.keyStates = states
                return
            }

            // 处理响应消息
            if let status = json["status"] as? String {
                if status == "success" {
                    if let action = json["action"] as? String, let key = json["key"] as? String {
                        if let latency = json["latency"] as? Double {
                            self.responseText = "\(action) \(key.uppercased()): 延迟 \(String(format: "%.2f", latency)) ms"
                        } else {
                            self.responseText = "\(action) \(key.uppercased()) 成功"
                        }
                    } else if let message = json["message"] as? String {
                        self.responseText = message
                    }

                    // 更新按键状态
                    if let states = json["key_states"] as? [String: Bool] {
                        self.keyStates = states
                    }
                } else if status == "error", let message = json["message"] as? String {
                    self.responseText = "错误: \(message)"
                    print("服务器错误: \(message)")
                }
            }
        }
    }

    func sendMessage(action: String, key: String) {
        print("发送消息: action=\(action), key='\(key)'")

        guard isConnected else {
            responseText = "未连接到服务器"
            return
        }

        // 验证键值 (除了get_state操作)
        if action != "get_state" && (key.isEmpty || key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty) {
            responseText = "错误: 键值不能为空"
            return
        }

        let message: [String: Any] = ["action": action, "key": key]

        guard let data = try? JSONSerialization.data(withJSONObject: message),
              let messageString = String(data: data, encoding: .utf8) else {
            responseText = "消息格式化失败"
            return
        }

        webSocketTask?.send(.string(messageString)) { [weak self] error in
            if let error = error {
                print("发送失败: \(error.localizedDescription)")
                DispatchQueue.main.async {
                    self?.responseText = "发送失败: \(error.localizedDescription)"
                }
            }
        }
    }

    func keyDown(key: String) {
        print("按下键: \(key)")
        sendMessage(action: "press_down", key: key)
    }

    func keyUp(key: String) {
        print("释放键: \(key)")
        sendMessage(action: "press_up", key: key)
    }
}

// MARK: - 自定义按钮组件
struct KeyButton: View {
    let keyName: String
    @ObservedObject var wsManager: WebSocketManager

    var body: some View {
        Button(action: {}) {
            Text(keyName)
                .font(.system(size: 40, weight: .bold))
                  .padding(.horizontal, 50)
                        .padding(.vertical,50)
                .padding(.all, 20)
                .background(
                    wsManager.keyStates[keyName.lowercased()] == true
                        ? (keyName == "X" ? Color.purple.opacity(0.2) : Color.red.opacity(0.7))
                        : (keyName == "X" ? Color.white : Color.black)
                )
                .foregroundColor(.white)
                .cornerRadius(8)
        }
        .simultaneousGesture(
            DragGesture(minimumDistance: 0)
                .onChanged { _ in
                    if wsManager.keyStates[keyName.lowercased()] != true {
                        wsManager.keyDown(key: keyName.lowercased())
                    }
                }
                .onEnded { _ in
                    wsManager.keyUp(key: keyName.lowercased())
                }
        )
    }
}

// MARK: - 主界面
struct ContentView: View {
    @StateObject private var wsManager = WebSocketManager()

    // 自定义每行按键排列方式
    private let layout: [[String]] = [
        ["X", "Z", "X", "Z", "X", "Z", "X", "Z", "X","Z"],
        ["Z", "X", "Z", "X", "Z", "X", "Z", "X", "Z", "X"], 
           ["X", "Z", "X", "Z", "X", "Z", "X", "Z", "X","Z"],
        ["Z", "X", "Z", "X", "Z", "X", "Z", "X", "Z", "X"], 
       ["X", "Z", "X", "Z", "X", "Z", "X", "Z", "X","Z"],
    ]

    var body: some View {
        VStack(spacing: 0) {
            ForEach(layout.indices, id: \.self) { row in
                HStack(spacing: 0) {
                    ForEach(layout[row], id: \.self) { keyName in
                        KeyButton(keyName: keyName, wsManager: wsManager)
                    }
                }
            }

            // 连接状态栏
            HStack {
                Circle()
                    .fill(wsManager.isConnected ? Color.green : Color.red)
                    .frame(width: 12, height: 12)

                Text(wsManager.isConnected ? "已连接" : "未连接")

                Spacer()

                Button(action: {
                    if wsManager.isConnected {
                        wsManager.disconnect()
                    } else {
                        wsManager.connect()
                    }
                }) {
                    Text(wsManager.isConnected ? "断开" : "连接")
                        .padding(.horizontal, 20)
                        .padding(.vertical, 8)
                        .background(wsManager.isConnected ? Color.red : Color.blue)
                        .foregroundColor(.white)
                        .cornerRadius(8)
                }
            }
            .padding(.horizontal)
        }
        .padding()
        .onAppear {
            // 启动时自动连接到服务器
            wsManager.connect()
        }
    }
}